package com.jadesoft.common.web;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.jadesoft.stock.util.Constants;

public class LoginFilter implements Filter {
	private ServletContext ctx;
	private static Logger log = Logger.getLogger(LoginFilter.class);
	private String[] ignore;

	public void destroy() {
		RequestContext.set(null);
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String uri = req.getRequestURI();
		log.debug("uri: "+uri);
		//过滤 不需要验证的
		for (int i = 0; i < ignore.length; i++) {
			if (uri.startsWith(ignore[i])) {
				chain.doFilter(request, response);
				return;
			}
		}
		// 验证需要验证是否登录
		if (req.getSession().getAttribute(Constants.LONGIN_USER) == null) {// 未登录或超时
			((HttpServletResponse) response).sendRedirect(Constants.LOGIN_PAGE);// 重定向到提示页面
			return;
		} else {// 已登录
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig cfg) throws ServletException {
		ignore = cfg.getInitParameter("ignore").split(",");
	}

}
